

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
///网络请求和数据库
class FrameWorkDemoPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('架构'),
      ),
      body: Column(
        children: <Widget>[
          ///  dro网络请求
          DroWidget(),
          /// database数据库
          DatabaseWidget(),
        ],
      ),
    );
  }
}

class DatabaseWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _DatabaseState();
  }

}

/// 数据库存储
/// 打开数据库
///  建表语句
///    增删查改
///  数据库升级
class _DatabaseState extends State<DatabaseWidget>{

  final UserEntityDao userEntityDao = new UserEntityDao();

  var index = 1;
  UserEntity? e;

  @override
  void initState() {
    super.initState();
    userEntityDao.init();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        TextButton(
          child: Text('插入'),
          onPressed: (() => {
            insert(),
          }),
        ),
        TextButton(
          child: Text('查询'),
          onPressed: (() => {
            query()
          }),
        ),
        TextButton(
          child: Text('更新'),
          onPressed: (() => {
            update(),
          }),
        ),
        TextButton(
          child: Text('删除'),
          onPressed: (() => {
            delete(),
          }),
        ),
//        TextButton(
//          child: Text('升级'),
//          onPressed: (() => {
//            upgrade(),
//          }),
//        ),
      ],
    );
  }

  insert() async {
    UserEntity entity = new UserEntity();
    entity.id = ++index;
    entity.name = "姓名:$index";
    entity.age = 25;
    entity.address = "地址";
    int result = await userEntityDao.insert(entity);
    print("插入：$result");
    e = entity;
  }

  query() async {
    List<UserEntity> list = await userEntityDao.query();
    print("query: ${list.length}");
    for(var entity in list) {
      print("id:${entity.id} name:${entity.name} age:${entity.age} address:${entity.address}");
    }
  }

  update() async {
    e!.name = '更新名称:${++index}';
    e!.age = 20;
    int result = await userEntityDao.update(e!);
    print("更新: $result");
  }

  delete() async {
    List<UserEntity> list = await userEntityDao.query();
    print("query: ${list.length}");
    for(var entity in list) {
      int result = await userEntityDao.delete(entity);
      print("删除:$result");
    }
  }

  upgrade() async {
    await userEntityDao.upgradeTable();
  }
}

class UserEntityDao{

  // ignore: non_constant_identifier_names
  final String TABLE_NAME = "table_user";

  UserEntityDao() {
    print("UserEntityDao");
  }

  init() async {
    bool isExit = await SqlManager.isTableExits("$TABLE_NAME");
    if(!isExit) {
      Database _database = await SqlManager.getDatabase();
      _database.execute("create table $TABLE_NAME (id interger primary key, name text not null, age integer, address text)");
    }
    print("init");
  }


  Future<int> insert(UserEntity entity) async {
    Database _database = await SqlManager.getDatabase();
//    Map<String, dynamic> values = new HashMap<String, dynamic>();
//    values.putIfAbsent("id", () => entity.id);
//    values.putIfAbsent("name", () => entity.name);
//    values.putIfAbsent("age", () => entity.age);
    return await _database.insert(TABLE_NAME, entity.toMap());
//    List<dynamic> list = new List();
//    list.add(entity.id);
//    list.add(entity.name);
//    list.add(entity.age);
//    list.add(entity.address);
//    return await _database.rawInsert("insert into $TABLE_NAME (id, name, age, address) values (?, ?, ?, ?)", list);
  }

  Future<List<UserEntity>> query() async {
    List<UserEntity> result = List.empty(growable: true);
    Database _database = await SqlManager.getDatabase();
    List<Map<String, dynamic>> list = await _database.rawQuery("select * from $TABLE_NAME");
    if(list.isNotEmpty) {
      for(var map in list) {
//        UserEntity entity = new UserEntity();
//        entity.id = map["id"];
//        entity.name = map["name"];
//        entity.age = map["age"];
//        result.add(entity);

        result.add(UserEntity.fromMap(map));
      }
    }
//    List<String> columns = new List();
//    columns.add("id");
//    columns.add("name");
//    columns.add("age");
//    columns.add("address");
//    List<Map<String, dynamic>> list = await _database.query(TABLE_NAME, columns: columns);
//    for(var map in list) {
//      UserEntity entity = new UserEntity();
//      entity.id = map["id"];
//      entity.name = map["name"];
//      entity.age = map["age"];
//      entity.address = map["address"];
//      result.add(entity);
//    }
    return result;
  }

  Future<int> update(UserEntity entity) async {
    Database _database = await SqlManager.getDatabase();
//    List<dynamic> list = new List();
//    list.add(entity.name);
//    list.add(entity.age);
//    list.add(entity.id);
//    return await _database.rawUpdate("update $TABLE_NAME set name = ?, age = ? where id = ?", list);
//    Map<String, dynamic> values = new Map();
//    values.putIfAbsent("name", () => entity.name);
//    values.putIfAbsent("age", () => entity.age);
//    values.putIfAbsent("address", () => entity.address);
    List<dynamic> list = List.empty(growable: true);
    list.add(entity.id);
    return await _database.update(TABLE_NAME, entity.toMap(), where: "id = ?", whereArgs: list);
  }

  Future<int> delete(UserEntity entity) async {
    Database _database = await SqlManager.getDatabase();
    List<dynamic> list = List.empty(growable: true);
    list.add(entity.id);
//    return await _database.rawDelete("delete from $TABLE_NAME where id = ?", list);
    return await _database.delete(TABLE_NAME, where: "id = ?", whereArgs: list);
  }

  upgradeTable() async {
    Database _database = await SqlManager.getDatabase();
    await _database.execute("alter table $TABLE_NAME add column address text");
  }
}

class UserEntity{
  int id = 0;
  String name = "";
  int age = 0;
  String address = "";

  UserEntity();

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = new Map();
    map["id"] = id;
    map["name"] = name;
    map["age"] = age;
    map["address"] = address;
    return map;
  }

  UserEntity.fromMap(Map<String, dynamic> map) {
    id = map["id"];
    name = map["name"];
    age = map["age"];
    address = map["address"];
  }
}

class SqlManager{
  static const DB_VERSION = 1;
  static const DB_NAME = "cz_flutter_demo.db";
  static Database? _database;

  static init() async{
    var databasePath = await getDatabasesPath();
    /// jion找不到需要导入import 'package:path/path.dart';
    String path = join(databasePath, DB_NAME);
    _database = await openDatabase(
        path,
        version: DB_VERSION,
        onCreate: (Database database, int version) async {
          print("onCreate: $version");
        },
        onUpgrade: (Database db, int oldVersion, int newVersion) async {
        print("onUpgrade   oldVersion: $oldVersion  newVersion:$newVersion");
      },
    );
  }

  static Future<Database> getDatabase() async {
    if(_database == null) {
      await init();
    }
    return _database!;
  }

  static isTableExits(String tableName) async {
    await getDatabase();
    var res = await _database!.rawQuery("select * from Sqlite_master where type = 'table' and name = '$tableName'");
    return res != null && res.length > 0;
  }

  static close() {
    _database?.close();
    _database = null;
  }
}

/// dro网络请求
class DroWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        TextButton(
          child: Text('Get请求'),
          onPressed: (() => {
            print('开始请求'),
            getHttp(),

          }),
        )
      ],
    );
  }


  void getHttp() async {
    var options = BaseOptions(
      baseUrl: "https://meet.smart0.cn/",
      connectTimeout: 6000,
      sendTimeout: 6000,
      receiveTimeout: 6000,
    );
    try{
      var entity = RequestEntity();
      Map body = Map();
      body["pageSize"] = 10;
      body["curPage"] = 1;
      body["querytype"] = 0;
      body["approverid"] = "123456";
      entity.body = body;
      var json = jsonEncode(entity);
      Map<String, String> params = Map();
      params['parameter'] = json;
      Dio dio = Dio(options);
      dio.interceptors.add(CustomInterceptors());
      dio.interceptors.add(LogInterceptor());
      var response = await dio.get("mono-biz-app-meet/CloudWorkApproval/getapprovalsum",
        queryParameters: params);
      var responseJson = jsonDecode("$response");
      ResponseEntity responseEntity = ResponseEntity.fromJson(responseJson);

      print("code: ${responseEntity.code}  msg: ${responseEntity.msg}");
    }catch(e) {
      print("error:$e");
    }

    var entity = ResponseEntity();
    entity.code = 9000;
    entity.msg = "请求成功";
    var json = jsonEncode(entity);
    print("json:$json");
    var jsonMap = jsonDecode(json);
    var entity2 = ResponseEntity.fromJson(jsonMap);
    print("222code: ${entity2.code}  msg: ${entity2.msg}");

  }

}

class CustomInterceptors extends InterceptorsWrapper{

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
    print("-----> request PATH:${options.path} \n method: ${options.method} params: ${options.queryParameters}");
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    print("<----- response PATH: ${response.requestOptions.path} \n statusCode: [${response.statusCode}]  result: ${response.data} ");
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    print("<----- PATH: ${err.requestOptions.path} \n statusCode: [${err.response?.statusCode}]");
  }
  // @override
  // Future onRequest(RequestOptions options) {
  //   print("-----> request PATH:${options?.path} \n method: ${options?.method} params: ${options?.queryParameters}");
  //   return super.onRequest(options);
  // }
  //
  // @override
  // Future onResponse(Response response) {
  //   print("<----- response PATH: ${response?.request?.path} \n statusCode: [${response?.statusCode}]  result: ${response?.data} ");
  //   return super.onResponse(response);
  // }
  //
  // @override
  // Future onError(DioError err) {
  //   print("<----- PATH: ${err?.request?.path} \n statusCode: [${err?.response?.statusCode}]");
  //   return super.onError(err);
  // }
}

class ResponseEntity {
  int code = 0;
  String msg = "";


  ResponseEntity();

  ResponseEntity.fromJson(Map<String, dynamic> json)
      : code = json['code'], msg = json['msg'];

  Map<String, dynamic> toJson() => {
    'code': code,
    'msg': msg,
  };
}

class RequestEntity {
  String token = "";
  String ver = "1.0";
  String sys = "android";
  String sysVer = "1.0";
  String channel = "";
  String lang = "";
  dynamic body;

  Map<String, dynamic> toJson() => {
  "token": token,
  "ver":  ver,
  "sys": sys,
  "sysVer": sysVer,
  "channel": channel,
  "lang":  lang,
  "body": body,
  };

//  Map toJson(){
//    Map map = Map();
//    map["token"] = token;
//    map["ver"] = ver;
//    map["sys"] = sys;
//    map["sysVer"] = sysVer;
//    map["channel"] = channel;
//    map["lang"] = lang;
//    map["body"] = body;
//    return map;
//  }
}